package com.wsoft.form.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.wsoft.core.exception.Asserts;
import com.wsoft.form.dto.WfFormTableRelationDTO;
import com.wsoft.form.entity.WfFormTableRelationEntity;
import com.wsoft.form.entity.WfFormVirtualColumnEntity;
import com.wsoft.form.enums.FormEnum;
import com.wsoft.form.manager.WfFormTableRelationManager;
import com.wsoft.form.manager.WfFormVirtualColumnManager;
import com.wsoft.form.service.IWfFormTableRelationService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 自定义表单-数据关联表 服务实现类
 * </p>
 *
 * @author Z001
 * @since 2024年09月05日 08:04:10
 */
@Service
public class WfFormTableRelationServiceImpl  implements IWfFormTableRelationService {

    @Resource
    private WfFormTableRelationManager relationManager;
    @Resource
    private WfFormVirtualColumnManager virtualColumnManager;
    /**
     * 添加表关联
     * @param dto
     * @return
     */
    @Override
    public boolean addOrUpdateColumnRelation(WfFormTableRelationDTO dto) {
        if (FormEnum.ONE.getValue().equals(dto.getIsMaster())) {
            //判断是否存在主表
            List<WfFormTableRelationEntity> list = relationManager.getMasterTable(dto.getFormId(), FormEnum.ONE.getValue());
            if (CollUtil.isNotEmpty(list) && !list.get(0).getTableId().equals(dto.getTableId())) {
                //主表只能存在一张
                Asserts.fail("[wform.table.master.one]");
            }
        }
        //保存关联关系
        WfFormTableRelationEntity relationEntity = Convert.convert(WfFormTableRelationEntity.class, dto);
        if(null == dto.getId()){
            return relationManager.save(relationEntity);
        }else{
            return relationManager.updateById(relationEntity);
        }
    }

    /**
     * 删除表关联
     * @param id
     * @return
     */
    @Override
    public boolean delColumnRelation(Long id,Long formId) {
        WfFormTableRelationEntity relation = relationManager.getById(id);
        //判断 该表是否有被主表关联
        if(FormEnum.ONE.getValue().equals(relation.getIsMaster())){
            //主表不能删除
            Asserts.fail("[wform.master.table.del]");
        }
        List<WfFormVirtualColumnEntity> columnEntityList = virtualColumnManager.getByAggregationTableId(formId,relation.getSlaveTableId());
        if(CollUtil.isNotEmpty(columnEntityList)){
            //主表关联了虚拟字段,不能删除
            Asserts.fail("[wform.master.virtual.del]");
        }
        return relationManager.removeById(id);
    }
}
